"""
数据库储存
"""
import os
from app import db
from app.utils import get_filehash
from datetime import datetime as dt


class InvBase(db.Model):
    """发票信息表"""
    __tablename__ = 'InvBase'
    id = db.Column(db.Integer, primary_key=True, unique=True)
    username = db.Column(db.String(100))
    date = db.Column(db.DateTime, default=dt.now)
    inv_code = db.Column(db.String(20))
    inv_num = db.Column(db.String(20))
    inv_date = db.Column(db.String(20))
    inv_chk = db.Column(db.String(30))
    inv_money = db.Column(db.String(20))
    path = db.Column(db.String(500))
    filehash = db.Column(db.String(40), unique=True)  # 储存文件hash，保证同样的文件不二次解析
    message = db.Column(db.Text)
    source = db.Column(db.String(10))
    state = db.Column(db.Boolean, default=True)

    def to_dict(self):
        return {
            "id": self.id,
            "username": self.username,
            "date": self.date.strftime("%Y-%m-%d"),
            "inv_code": self.inv_code,
            "inv_num": self.inv_num,
            "inv_date": self.inv_date,
            "inv_chk": self.inv_chk,
            "inv_money": self.inv_money,
            "inv_path": self.path,
            "filehash": self.filehash,
            "message": self.message,
            "source": self.source,
            "state": self.state
        }
    @classmethod
    def from_dict(cls, data):
        inv = InvBase(filehash=data["filehash"])
        keys = [kname for kname in inv.__dir__() if not kname.startswith('_')]
        for k, v in data.items():
            if k in keys:
                inv.__setattr__(k, v)
        db.session.add(inv)
        db.session.commit()
        return inv

    @classmethod
    def exists(cls, path):
        """判断对应文件的发票信息是否存在"""
        filehash = get_filehash(path)
        inv_base = InvBase.query.filter_by(filehash=filehash).first()
        return inv_base.to_dict() if inv_base else None
        
    def __repr__(self):
        return f'<Inv {os.path.basename(self.path)}>'
